﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "新增生产工单";
}
<link href="~/css/site.css" rel="stylesheet" />
<link href="~/layui/css/layui.css" rel="stylesheet" />

<script src="~/layui/layui.js"></script>
<script src="~/js/site.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">新增生产工单</h3>
                    <div class="card-tools">
                        <a href="/Home/GetWorkOrder" class="btn btn-secondary btn-sm">
                            <i class="layui-icon layui-icon-return"></i> 返回列表
                        </a>
                    </div>
                </div>
                <div class="card-body">
                    <form id="addWorkOrderForm">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="workOrderCode" class="form-label">工单编号 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="workOrderCode" name="workOrderCode" 
                                           placeholder="请输入工单编号" required>
                                    <div class="invalid-feedback">
                                        请输入工单编号
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="workOrderName" class="form-label">工单名称 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="workOrderName" name="workOrderName" 
                                           placeholder="请输入工单名称" required>
                                    <div class="invalid-feedback">
                                        请输入工单名称
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="leaderId" class="form-label">负责人 <span class="text-danger">*</span></label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" id="leaderName" name="leaderName" 
                                               placeholder="请选择负责人" readonly required>
                                        <input type="hidden" id="leaderId" name="leaderId" required>
                                        <div class="input-group-append">
                                            <button type="button" class="btn btn-outline-secondary" id="btnSelectLeader">
                                                <i class="layui-icon layui-icon-search"></i> 选择
                                            </button>
                                        </div>
                                    </div>
                                    <div class="invalid-feedback">
                                        请选择负责人
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="orderNum" class="form-label">订单数量 <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="orderNum" name="orderNum" 
                                           placeholder="请输入订单数量" required min="1">
                                    <div class="invalid-feedback">
                                        请输入有效的订单数量
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="productId" class="form-label">产品 <span class="text-danger">*</span></label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" id="productName" name="productName" 
                                               placeholder="请选择产品" readonly required>
                                        <input type="hidden" id="productId" name="productId" required>
                                        <div class="input-group-append">
                                            <button type="button" class="btn btn-outline-secondary" id="btnSelectProduct">
                                                <i class="layui-icon layui-icon-search"></i> 选择
                                            </button>
                                        </div>
                                    </div>
                                    <div class="invalid-feedback">
                                        请选择产品
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="workOrderDate" class="form-label">工单日期 <span class="text-danger">*</span></label>
                                    <input type="datetime-local" class="form-control" id="workOrderDate" name="workOrderDate" 
                                           required>
                                    <div class="invalid-feedback">
                                        请选择工单日期
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="worderOrderDesc" class="form-label">工单描述</label>
                                    <textarea class="form-control" id="worderOrderDesc" name="worderOrderDesc" 
                                              rows="3" placeholder="请输入工单描述（可选）"></textarea>
                                </div>
                            </div>
                        </div>

                        <div class="row mt-4">
                            <div class="col-12">
                                <div class="form-group text-center">
                                    <button type="submit" class="btn btn-primary" id="btnSubmit">
                                        <i class="layui-icon layui-icon-ok"></i> 提交
                                    </button>
                                    <button type="button" class="btn btn-secondary ml-2" id="btnReset">
                                        <i class="layui-icon layui-icon-refresh"></i> 重置
                                    </button>
                                    <a href="/Home/GetWorkOrder" class="btn btn-outline-secondary ml-2">
                                        <i class="layui-icon layui-icon-close"></i> 取消
                                    </a>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 产品选择对话框 -->
<div class="modal fade" id="productModal" tabindex="-1" role="dialog" aria-labelledby="productModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="productModalLabel">选择产品</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="row mb-3">
                    <div class="col-md-6">
                        <div class="input-group">
                            <input type="text" class="form-control" id="productSearchInput" placeholder="搜索产品名称、编码或规格...">
                            <div class="input-group-append">
                                <button class="btn btn-outline-secondary" type="button" id="btnSearchProduct">
                                    <i class="layui-icon layui-icon-search"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table table-bordered table-hover" id="productTable">
                        <thead class="thead-light">
                            <tr>
                                <th width="60">序号</th>
                                <th>产品ID</th>
                                <th>产品名称</th>
                                <th>产品编码</th>
                                <th>规格</th>
                                <th>单位</th>
                                <th>分类</th>
                                <th>计划开始</th>
                                <th>计划结束</th>
                                <th>计划数量</th>
                                <th width="100">操作</th>
                            </tr>
                        </thead>
                        <tbody id="productTableBody">
                            <!-- 数据将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>
                <div id="productLoading" class="text-center" style="display: none;">
                    <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i> 加载中...
                </div>
                <div id="productNoData" class="text-center text-muted" style="display: none;">
                    暂无产品数据
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>

<!-- 负责人选择对话框 -->
<div class="modal fade" id="leaderModal" tabindex="-1" role="dialog" aria-labelledby="leaderModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="leaderModalLabel">选择负责人</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="row mb-3">
                    <div class="col-md-6">
                        <div class="input-group">
                            <input type="text" class="form-control" id="leaderSearchInput" placeholder="搜索负责人姓名或部门...">
                            <div class="input-group-append">
                                <button class="btn btn-outline-secondary" type="button" id="btnSearchLeader">
                                    <i class="layui-icon layui-icon-search"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table table-bordered table-hover" id="leaderTable">
                        <thead class="thead-light">
                            <tr>
                                <th width="80">序号</th>
                                <th>负责人ID</th>
                                <th>负责人姓名</th>
                                <th>所属部门</th>
                                <th width="100">操作</th>
                            </tr>
                        </thead>
                        <tbody id="leaderTableBody">
                            <!-- 数据将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>
                <div id="leaderLoading" class="text-center" style="display: none;">
                    <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i> 加载中...
                </div>
                <div id="leaderNoData" class="text-center text-muted" style="display: none;">
                    暂无负责人数据
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function () {
        // 设置默认日期为当前时间
        const now = new Date();
        const localDateTime = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
        $('#workOrderDate').val(localDateTime);

        // 表单提交事件
        $('#addWorkOrderForm').on('submit', function (e) {
            e.preventDefault();
            submitForm();
        });

        // 重置按钮事件
        $('#btnReset').click(function () {
            resetForm();
        });

        // 负责人选择按钮事件
        $('#btnSelectLeader').click(function () {
            openLeaderModal();
        });

        // 负责人搜索按钮事件
        $('#btnSearchLeader').click(function () {
            searchLeaders();
        });

        // 负责人搜索框回车事件
        $('#leaderSearchInput').keypress(function (e) {
            if (e.which === 13) {
                searchLeaders();
            }
        });

        // 产品选择按钮事件
        $('#btnSelectProduct').click(function () {
            openProductModal();
        });

        // 产品搜索按钮事件
        $('#btnSearchProduct').click(function () {
            searchProducts();
        });

        // 产品搜索框回车事件
        $('#productSearchInput').keypress(function (e) {
            if (e.which === 13) {
                searchProducts();
            }
        });



        // 提交表单
        function submitForm() {
            // 验证表单
            if (!validateForm()) {
                return;
            }

            // 显示加载状态
            showLoading();

            // 收集表单数据
            const formData = {
                workOrderCode: $('#workOrderCode').val().trim(),
                workOrderName: $('#workOrderName').val().trim(),
                leaderId: parseInt($('#leaderId').val()),
                orderNum: parseInt($('#orderNum').val()),
                worderOrderDesc: $('#worderOrderDesc').val().trim(),
                workOrderDate: $('#workOrderDate').val() + ':00.000Z', // 转换为ISO格式
                productId: parseInt($('#productId').val())
            };

            // 调用后端API
            $.ajax({
                url: 'http://localhost:5025/api/Production/AddWorkOrder',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function (response) {
                    hideLoading();
                    if (response.code === 200) {
                        showSuccess('添加生产工单成功！');
                        // 延迟跳转到列表页面
                        setTimeout(function () {
                            window.location.href = '/Home/GetWorkOrder';
                        }, 1500);
                    } else {
                        showError('添加失败：' + response.msg);
                    }
                },
                error: function (xhr, status, error) {
                    hideLoading();
                    let errorMsg = '请求失败';
                    if (xhr.responseJSON && xhr.responseJSON.msg) {
                        errorMsg += '：' + xhr.responseJSON.msg;
                    } else {
                        errorMsg += '：' + error;
                    }
                    showError(errorMsg);
                }
            });
        }

        // 验证表单
        function validateForm() {
            let isValid = true;
            const requiredFields = [
                'workOrderCode',
                'workOrderName', 
                'leaderId',
                'orderNum',
                'workOrderDate',
                'productId'
            ];

            // 清除之前的验证状态
            $('.form-control').removeClass('is-invalid');

            // 验证必填字段
            requiredFields.forEach(function (fieldName) {
                const field = $('#' + fieldName);
                const value = field.val().trim();
                
                if (!value) {
                    field.addClass('is-invalid');
                    isValid = false;
                } else {
                    field.addClass('is-valid');
                }
            });

            // 验证数字字段
            const numberFields = ['orderNum'];
            numberFields.forEach(function (fieldName) {
                const field = $('#' + fieldName);
                const value = parseInt(field.val());
                
                if (isNaN(value) || value <= 0) {
                    field.addClass('is-invalid');
                    isValid = false;
                }
            });

            // 验证产品选择
            const productId = $('#productId').val();
            if (!productId) {
                $('#productName').addClass('is-invalid');
                isValid = false;
            }

            // 验证负责人选择
            const leaderId = $('#leaderId').val();
            if (!leaderId) {
                $('#leaderName').addClass('is-invalid');
                isValid = false;
            }

            // 验证订单数量
            const orderNum = parseInt($('#orderNum').val());
            if (orderNum <= 0) {
                $('#orderNum').addClass('is-invalid');
                isValid = false;
            }

            return isValid;
        }

        // 重置表单
        function resetForm() {
            $('#addWorkOrderForm')[0].reset();
            $('.form-control').removeClass('is-invalid is-valid');
            
            // 清空负责人选择
            $('#leaderId').val('');
            $('#leaderName').val('');
            
            // 清空产品选择
            $('#productId').val('');
            $('#productName').val('');
            
            // 重新设置默认日期
            const now = new Date();
            const localDateTime = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
            $('#workOrderDate').val(localDateTime);
        }

        // 显示加载状态
        function showLoading() {
            $('#btnSubmit').prop('disabled', true).html('<i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i> 提交中...');
        }

        // 隐藏加载状态
        function hideLoading() {
            $('#btnSubmit').prop('disabled', false).html('<i class="layui-icon layui-icon-ok"></i> 提交');
        }

        // 显示成功消息
        function showSuccess(message) {
            layer.msg(message, {
                icon: 1,
                time: 2000
            });
        }

        // 显示错误消息
        function showError(message) {
            layer.msg(message, {
                icon: 2,
                time: 3000
            });
        }

        // 实时验证
        $('.form-control').on('blur', function () {
            const field = $(this);
            const value = field.val().trim();
            
            if (field.attr('required') && !value) {
                field.addClass('is-invalid');
            } else {
                field.removeClass('is-invalid').addClass('is-valid');
            }
        });

        // 负责人相关函数
        let leaderData = [];

        // 打开负责人选择对话框
        function openLeaderModal() {
            $('#leaderModal').modal('show');
            loadLeaderData();
        }

        // 加载负责人数据
        function loadLeaderData() {
            showLeaderLoading();
            
            $.ajax({
                url: 'http://localhost:5025/api/Production/GetLeader',
                type: 'GET',
                success: function (response) {
                    hideLeaderLoading();
                    if (response.code === 200) {
                        leaderData = response.data || [];
                        renderLeaderTable(leaderData);
                    } else {
                        showLeaderError('加载负责人数据失败：' + response.msg);
                    }
                },
                error: function (xhr, status, error) {
                    hideLeaderLoading();
                    showLeaderError('请求失败：' + error);
                }
            });
        }

        // 搜索负责人
        function searchLeaders() {
            const keyword = $('#leaderSearchInput').val().trim().toLowerCase();
            
            if (!keyword) {
                renderLeaderTable(leaderData);
                return;
            }

            const filteredData = leaderData.filter(function (leader) {
                return leader.leaderName.toLowerCase().includes(keyword) ||
                       leader.departmentName.toLowerCase().includes(keyword) ||
                       leader.leaderId.toString().includes(keyword);
            });

            renderLeaderTable(filteredData);
        }

        // 渲染负责人表格
        function renderLeaderTable(data) {
            const tbody = $('#leaderTableBody');
            tbody.empty();

            if (data.length === 0) {
                $('#leaderNoData').show();
                return;
            }

            $('#leaderNoData').hide();
            data.forEach((leader, index) => {
                const row = `
                    <tr>
                        <td>${index + 1}</td>
                        <td>${leader.leaderId}</td>
                        <td>${leader.leaderName}</td>
                        <td>${leader.departmentName}</td>
                        <td>
                            <button type="button" class="btn btn-sm btn-primary" onclick="selectLeader(${leader.leaderId}, '${leader.leaderName}', '${leader.departmentName}')">
                                选择
                            </button>
                        </td>
                    </tr>
                `;
                tbody.append(row);
            });
        }

        // 选择负责人
        window.selectLeader = function (leaderId, leaderName, departmentName) {
            $('#leaderId').val(leaderId);
            $('#leaderName').val(leaderName + ' (' + departmentName + ')');
            
            // 清除验证状态
            $('#leaderName').removeClass('is-invalid').addClass('is-valid');
            
            // 关闭对话框
            $('#leaderModal').modal('hide');
            
            // 显示成功提示
            layer.msg('已选择负责人：' + leaderName, {
                icon: 1,
                time: 1500
            });
        };

        // 显示负责人加载状态
        function showLeaderLoading() {
            $('#leaderLoading').show();
            $('#leaderTable').hide();
            $('#leaderNoData').hide();
        }

        // 隐藏负责人加载状态
        function hideLeaderLoading() {
            $('#leaderLoading').hide();
            $('#leaderTable').show();
        }

        // 显示负责人错误信息
        function showLeaderError(message) {
            $('#leaderTableBody').html(`<tr><td colspan="5" class="text-center text-danger">${message}</td></tr>`);
            $('#leaderTable').show();
        }

        // 产品相关函数
        let productData = [];

        // 打开产品选择对话框
        function openProductModal() {
            $('#productModal').modal('show');
            loadProductData();
        }

        // 加载产品数据
        function loadProductData() {
            showProductLoading();
            
            $.ajax({
                url: 'http://localhost:5025/api/Production/GetProductItem',
                type: 'GET',
                success: function (response) {
                    hideProductLoading();
                    if (response.code === 200) {
                        productData = response.data || [];
                        renderProductTable(productData);
                    } else {
                        showProductError('加载产品数据失败：' + response.msg);
                    }
                },
                error: function (xhr, status, error) {
                    hideProductLoading();
                    showProductError('请求失败：' + error);
                }
            });
        }

        // 搜索产品
        function searchProducts() {
            const keyword = $('#productSearchInput').val().trim().toLowerCase();
            
            if (!keyword) {
                renderProductTable(productData);
                return;
            }

            const filteredData = productData.filter(function (product) {
                return product.productName.toLowerCase().includes(keyword) ||
                       product.productCode.toLowerCase().includes(keyword) ||
                       product.specification.toLowerCase().includes(keyword) ||
                       product.productId.toString().includes(keyword);
            });

            renderProductTable(filteredData);
        }

        // 渲染产品表格
        function renderProductTable(data) {
            const tbody = $('#productTableBody');
            tbody.empty();

            if (data.length === 0) {
                $('#productNoData').show();
                $('#productTable').hide();
                return;
            }

            $('#productNoData').hide();
            $('#productTable').show();
            
            data.forEach((product, index) => {
                const row = `
                    <tr>
                        <td>${index + 1}</td>
                        <td>${product.productId}</td>
                        <td>${product.productName}</td>
                        <td>${product.productCode}</td>
                        <td>${product.specification}</td>
                        <td>${product.unitName}</td>
                        <td>${product.classify}</td>
                        <td>${formatDateTime(product.planStart)}</td>
                        <td>${formatDateTime(product.planEnd)}</td>
                        <td>${product.planNum}</td>
                        <td>
                            <button type="button" class="btn btn-sm btn-primary" onclick="selectProduct(${product.productId}, '${product.productName}', '${product.productCode}', '${product.specification}')">
                                选择
                            </button>
                        </td>
                    </tr>
                `;
                tbody.append(row);
            });
        }

        // 选择产品
        window.selectProduct = function (productId, productName, productCode, specification) {
            $('#productId').val(productId);
            $('#productName').val(productName + ' (' + productCode + ')');
            
            // 清除验证状态
            $('#productName').removeClass('is-invalid').addClass('is-valid');
            
            // 关闭对话框
            $('#productModal').modal('hide');
            
            // 显示成功提示
            layer.msg('已选择产品：' + productName, {
                icon: 1,
                time: 1500
            });
        };

        // 格式化日期时间
        function formatDateTime(dateTimeString) {
            if (!dateTimeString) return '';
            const date = new Date(dateTimeString);
            return date.toLocaleString('zh-CN', { 
                year: 'numeric', 
                month: '2-digit', 
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        // 显示产品加载状态
        function showProductLoading() {
            $('#productLoading').show();
            $('#productTable').hide();
            $('#productNoData').hide();
        }

        // 隐藏产品加载状态
        function hideProductLoading() {
            $('#productLoading').hide();
            $('#productTable').show();
        }

        // 显示产品错误信息
        function showProductError(message) {
            $('#productTableBody').html(`<tr><td colspan="10" class="text-center text-danger">${message}</td></tr>`);
            $('#productTable').show();
            $('#productNoData').hide();
        }
    });
</script>

<style>
    .card {
        margin: 20px;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    }
    
    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #f8f9fa;
        border-bottom: 1px solid #dee2e6;
    }
    
    .form-label {
        font-weight: 500;
        margin-bottom: 0.5rem;
    }
    
    .form-control:focus {
        border-color: #80bdff;
        box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
    }
    
    .is-valid {
        border-color: #28a745;
    }
    
    .is-invalid {
        border-color: #dc3545;
    }
    
    .btn {
        padding: 0.375rem 0.75rem;
        font-size: 1rem;
        line-height: 1.5;
        border-radius: 0.25rem;
    }
    
    .btn:disabled {
        opacity: 0.65;
        cursor: not-allowed;
    }
    
    .layui-icon {
        font-size: 14px;
        margin-right: 4px;
    }
    
    .text-danger {
        color: #dc3545 !important;
    }
    
    .form-group {
        margin-bottom: 1rem;
    }
    
    .card-tools {
        display: flex;
        align-items: center;
    }
    
    /* 负责人选择对话框样式 */
    .modal-lg {
        max-width: 900px;
    }
    
    .modal-body {
        max-height: 500px;
        overflow-y: auto;
    }
    
    .table th {
        background-color: #f8f9fa;
        border-color: #dee2e6;
        font-weight: 500;
    }
    
    .btn-sm {
        padding: 0.25rem 0.5rem;
        font-size: 0.875rem;
    }
    
    #leaderSearchInput {
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
    }
    
    #btnSearchLeader {
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
    }
    
    .input-group-append .btn {
        border-left: 0;
    }
    
    /* 产品选择对话框样式 */
    .modal-xl {
        max-width: 1200px;
    }
    
    #productSearchInput {
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
    }
    
    #btnSearchProduct {
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
    }
    

</style>